package com.noble.meether.fragment.rob;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.BaseFragment;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.logic.socket.AutoConnectMgr;
import com.noble.library.log.PSP;
import com.noble.library.log.PToast;
import com.noble.library.utils.ScreenUtils;
import com.noble.library.view.custom.state.CustomRecyclerView;
import com.noble.library.widget.RecyclerView.RecyclerAnimUtil;
import com.noble.meether.MeetUIShow;
import com.noble.meether.R;
import com.noble.meether.fragment.rob.adapter.RobAdapter;
import com.noble.meether.fragment.rob.bean.RobList;
import com.noble.meether.fragment.rob.util.RobUtil;

import org.json.JSONObject;

/**
 * 女性：抢聊大厅
 */
public class RobFragment extends BaseFragment implements RobUtil.PoolCallback, View.OnClickListener, RequestComplete {
    private CustomRecyclerView customLayout;
    private RecyclerView poolList;
    private RobAdapter robAdapter;
    private TextView tv_star;

    private static final String NOTICE_SHOW = "notice_show";
    private SwitchCompat switchCompat;
    private RelativeLayout rlNotice;

    private boolean isHidden;     // 页面是否隐藏
    private UserDetail userDetail;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.rob_fragment);
        initView();
        return getContentView();
    }

    private void initView() {
        userDetail = ModuleMgr.getCenterMgr().getMyInfo();
        float toDpMutliple = ScreenUtils.toDpMultiple(getActivity());
        customLayout = (CustomRecyclerView) findViewById(R.id.list_pool);
        customLayout.showNoData();

        initSwitchCompat();
        findViewById(R.id.ll_point).setOnClickListener(this);
        tv_star = (TextView) findViewById(R.id.tv_star);
        poolList = customLayout.getRecyclerView();
        poolList.setLayoutManager(new LinearLayoutManager(getContext()));
        poolList.addItemDecoration(new ItemSpaces((int) (10 * toDpMutliple)));
        robAdapter = new RobAdapter(getContext());
        poolList.setAdapter(robAdapter);
        RecyclerAnimUtil.runLeftAnimation(poolList);
        RobUtil.getInstance().setPoolCallback(this);
        tv_star.setText(String.valueOf(userDetail.getStar()));
    }

    private void initSwitchCompat() {
        rlNotice = (RelativeLayout) findViewById(R.id.rl_notice);
        boolean showNotice = PSP.getInstance().getBoolean(NOTICE_SHOW, true);
        rlNotice.setVisibility(showNotice ? View.VISIBLE : View.GONE);
        switchCompat = (SwitchCompat) findViewById(R.id.switch_compat);
        findViewById(R.id.btn_close_notice).setOnClickListener(this);
        boolean switchStatus = RobUtil.getInstance().getRobNotice();
        switchCompat.setChecked(switchStatus);
        switchCompat.setOnCheckedChangeListener((compoundButton, b) -> {
            // b = true: 打开  false: 关闭
            PToast.showShort(b ? "抢聊通知已开启" : "抢聊通知已关闭");
            ModuleMgr.getPushMgr().resetRobTag(b);
        });
    }

    private void stopPool() {
        RobUtil.getInstance().stopPoolTime();
        customLayout.showNoData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {         // false: 处于当前fragment
        super.onHiddenChanged(hidden);
        isHidden = hidden;
        if (hidden) {
            stopPool();
            return;
        }
        RobUtil.getInstance().startPoolTime();
        AutoConnectMgr.getInstance().sendHeartData(); // 发送心跳，检测TCP连接状态
        ModuleMgr.getCenterMgr().reqMyPartInfo(new String[]{"Star", "AmountStar", "StatusAuth"}, this);
    }

    @Override
    public void onPause() { // 停止轮询
        super.onPause();
        stopPool();
    }

    @Override
    public void onResume() {  // 开启轮询
        super.onResume();
        if (!isHidden) {
            RobUtil.getInstance().startPoolTime();
        }
    }

    @Override
    public void onRefresh(HttpResponse response) {
        if (!response.isOk()) {
            customLayout.showNoData();
            return;
        }
        RobList list = (RobList) response.getBaseData();
        if (list.getRobList().size() <= 0) {
            customLayout.showNoData();
            return;
        }
        RecyclerAnimUtil.runLeftAnimation(poolList);
        robAdapter.setList(list.getRobList());
        customLayout.showRecyclerView();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_point:
                MeetUIShow.showMyPointAct(getContext());
                break;
            case R.id.btn_close_notice:
                PSP.getInstance().put(NOTICE_SHOW, false);
                if (rlNotice != null) {
                    rlNotice.setVisibility(View.GONE);
                }
                break;
        }
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        JSONObject jsonObject = response.getResponseObject();
        userDetail.setStar(jsonObject.optDouble("Star"));
        userDetail.setAmountStar(jsonObject.optDouble("AmountStar"));
        userDetail.setStatusAuth(jsonObject.optInt("StatusAuth"));
        tv_star.setText(String.valueOf(userDetail.getStar()));
    }

    private class ItemSpaces extends RecyclerView.ItemDecoration {
        private int space;

        public ItemSpaces(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.right = space / 2;
            outRect.left = space / 2;
            outRect.top = space;
        }
    }
}
